import Vue from 'vue';
import VueRouter from 'vue-router';
import store from './store';
import IndexView from './components/Index';

import LoginView from './components/Login';
import RegisterView from './components/Register'
import NotFoundView from './components/NotFound';

import GeneralView from './components/views/General'
import AppsView from './components/views/Apps'
import AppDetailView from './components/views/AppDetail';
import DevicesView from './components/views/Devices'
import SessionsView from './components/views/Sessions'
import DeviceDetailView from './components/views/DeviceDetail';
import ProfileView from './components/views/Profile';

Vue.use(VueRouter)

const routes = [{
    path: '/login',
    name: 'Login',
    component: LoginView
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterView
  },
  {
    path: '*',
    name: 'NotFound',
    component: NotFoundView,
  },
  {
    path: '/',
    name: 'Index',
    component: IndexView,
    redirect: '/general',
    children: [{
        path: 'general',
        name: 'General',
        component: GeneralView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'apps',
        name: 'Apps',
        component: AppsView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'apps/:appid',
        name: 'AppDetail',
        component: AppDetailView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'devices',
        name: 'Devices',
        component: DevicesView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'devices/:devid',
        name: 'DeviceDetail',
        component: DeviceDetailView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'sessions',
        name: 'Sessions',
        component: SessionsView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: ProfileView,
        meta: {
          requireAuth: true
        }
      },

    ]
  },
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (store.getters.isLogin) {
      next();
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      });
    }
  } else {
    next();
  }
});

//此项为了解决左侧导航菜单不自动隐藏的bug
router.afterEach((to, from) => {
  $("body").removeClass("sidebar-open").removeClass("sidebar-collapse").trigger("collapsed.pushMenu");
});

export default router;